package kr.hkit.android_bookmgr.activity;

import java.io.File;
import java.util.Calendar;
import java.util.GregorianCalendar;

import kr.hkit.android_bookmgr.R;
import kr.hkit.android_bookmgr.DAO.BookDAO;
import kr.hkit.android_bookmgr.util.ImageUtil;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;

public class AddBookDirectlyActivity extends Activity {

	//도서등록 - 직접입력
	static final int CALL_CAMERA = 0;
	static final int CALL_GALLERY = 1;
	
	private Intent intent = null;
	private ImageView mImage;
	private String mPathCamera = null;
	private String mPathGallery = null;
	
	private BookDAO mBookMgr;
	
	private EditText startdate, enddate;
	private int mYear, mMonth, mDay;
	private int mHour, mMin, mSec;
	private int pos, imgClick;
	
	private LinearLayout startlinear, endlinear;
	private View datepicker;
	private String mRealPathGallery;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.addbook_directly_activity);
		
		ActionBar mActionBar = getActionBar();
		mActionBar.setDisplayHomeAsUpEnabled(true); 
		mActionBar.setHomeButtonEnabled(true);
		
		// 독서시작일, 독서완료일 용
		startdate = (EditText) findViewById(R.id.addbook_direct_startdateedit);
		startdate.setOnFocusChangeListener(mOnFocusChangeListener);
		enddate = (EditText) findViewById(R.id.addbook_direct_enddateedit);
		enddate.setOnFocusChangeListener(mOnFocusChangeListener);

		startlinear = (LinearLayout) findViewById(R.id.addbook_direct_startdatelinear);
		endlinear = (LinearLayout) findViewById(R.id.addbook_direct_enddatelinear);

		calendar();
		mBookMgr = BookDAO.getInstance(this);
		 
		Spinner spin = (Spinner) findViewById(R.id.addbook_direct_status);
		ArrayAdapter<CharSequence> adspin = ArrayAdapter.createFromResource(this, 
				R.array.addbook_direct_statuslist, android.R.layout.simple_spinner_dropdown_item);
		spin.setAdapter(adspin);
	
		spin.setOnItemSelectedListener(new OnItemSelectedListener() {

			//스피너 - 상태부분
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,int position, long id) {
				
				pos = position; 
				
				if(position==2){ //읽는 중 - 독서시작일만 활성화 
					startlinear.setVisibility(LinearLayout.VISIBLE);
					endlinear.setVisibility(LinearLayout.GONE);
				}else if(position==3){ //읽기 완료 - 독서시작일, 완료일 둘다 활성화 
					startlinear.setVisibility(LinearLayout.VISIBLE);
					endlinear.setVisibility(LinearLayout.VISIBLE);
				}else{ //없음, 읽을예정은 필요없으니까 invisible
					startlinear.setVisibility(LinearLayout.GONE);
					endlinear.setVisibility(LinearLayout.GONE);
				}
			}//spinner

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				
			}
		});
		
		//카메라
		mImage = (ImageView) findViewById(R.id.addbook_direct_img);
		mPathCamera = Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+mYear+"_"+(mMonth+1)+"_"+mDay+"_"+mHour+"_"+mMin+"_"+mSec+".jpg";
		
		
	}//onCreate
	
	
	public boolean onOptionsItemSelected(android.view.MenuItem item) {
		switch (item.getItemId()) {
			case android.R.id.home:
				  Intent intent = new Intent(this, BookListActivity.class); 
				  intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //액티비티 쌓이지 않기위해. 바로메인
				  startActivity(intent);
				  break;
		}
		return super.onOptionsItemSelected(item);

	}; //홈으로 이동

	
	private void calendar(){
		
		Calendar cal = new GregorianCalendar();
		mYear = cal.get(Calendar.YEAR);
		mMonth = cal.get(Calendar.MONTH);
		mDay = cal.get(Calendar.DAY_OF_MONTH);
		mHour = cal.get(Calendar.HOUR_OF_DAY);
		mMin = cal.get(Calendar.MINUTE);
		mSec = cal.get(Calendar.SECOND);
		
	}
	
	
	@Override
	protected void onPause() {
		super.onPause();
		mBookMgr.close();
	}
	
	
	OnFocusChangeListener mOnFocusChangeListener = new OnFocusChangeListener() {
		
		@Override
		public void onFocusChange(View v, boolean hasFocus) {
			datepicker = v;
			if(hasFocus)
				new DatePickerDialog(AddBookDirectlyActivity.this, mDateSetListener, mYear, mMonth, mDay).show();
		}
	};
	
	public void mOnClick(View v) {
		
		datepicker = v;
		
		switch(v.getId()) {
		case R.id.addbook_direct_img: //이미지 클릭 시, 직찍 혹은 갤러리 이동
			new AlertDialog.Builder(this)
			.setTitle("이미지 선택 방법을 고르시오.")
			.setItems(R.array.addbook_direct_pickimg, 
					new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					String[] pickimg = getResources().getStringArray(R.array.addbook_direct_pickimg);
					Toast.makeText(getBaseContext(), pickimg[which]+"를 선택하셨습니다.", Toast.LENGTH_SHORT).show();
					
					imgClick = which;
					
					if(which==0){ //0은 카메라실행. //1은 갤러리
						intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
						intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mPathCamera)));
						startActivityForResult(intent, CALL_CAMERA);
					}else{
						intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
						intent.setType(MediaStore.Images.Media.CONTENT_TYPE); //인터넷방법
						startActivityForResult(intent, CALL_GALLERY);
					}
					
				}
			})
			.setNegativeButton("취소", null)
			.show();
			break;
		
		case R.id.addbook_direct_add: //등록버튼 눌렀을 때
			
			EditText name = (EditText) findViewById(R.id.addbook_direct_name);
			EditText author = (EditText) findViewById(R.id.addbook_direct_author);
			EditText publisher = (EditText) findViewById(R.id.addbook_direct_publisher);
			EditText totalpage = (EditText) findViewById(R.id.addbook_direct_totalpage);
			EditText startdate = (EditText) findViewById(R.id.addbook_direct_startdateedit);
			EditText enddate = (EditText) findViewById(R.id.addbook_direct_enddateedit);

			ContentValues addRowValue = new ContentValues();
			addRowValue.put("name", name.getText().toString().trim());
			addRowValue.put("author", author.getText().toString().trim());
			addRowValue.put("publisher", publisher.getText().toString().trim());
			addRowValue.put("totalpage", totalpage.getText().toString().trim());
			if(pos==3){
				addRowValue.put("currentpage", totalpage.getText().toString().trim());
			}
			addRowValue.put("status",pos);
			
			if(imgClick==0){
				addRowValue.put("bookimg", mPathCamera.trim()); //직찍 경로
				addRowValue.put("imgtype", 0); //imgtype 0이면 직찍
			}else{
				addRowValue.put("bookimg", mPathGallery.trim()); //갤러리 경로
				addRowValue.put("imgtype", 1); //imgtype 1이면  갤러리
			}
			addRowValue.put("startdate", startdate.getText().toString().trim());
			addRowValue.put("enddate", enddate.getText().toString().trim());				
			
			mBookMgr.insertBook(addRowValue);
			Toast.makeText(AddBookDirectlyActivity.this, "등록되었습니다.", Toast.LENGTH_SHORT).show();
			
			finish();
			
			break;
			
		case R.id.addbook_direct_cancle:
			finish();
			break;
			}//switch
		}//mOnClick
	
	
	DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			
			if(datepicker.getId()==R.id.addbook_direct_startdateedit){
				startdate.setText(String.format("%d/%02d/%d", mYear, mMonth+1, mDay));
			}else{
				enddate.setText(String.format("%d/%02d/%d", mYear, mMonth+1, mDay));
			}
		}
	};//DatePickerDialog
	private int code;

	//카메라 결과
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		code = requestCode;
		if(resultCode==RESULT_OK){
			
			switch(requestCode){
			case CALL_CAMERA:

				updateImageView();
				//Toast.makeText(this, mPathCamera, Toast.LENGTH_LONG).show();
				break;
				
			case CALL_GALLERY:
				
				//사진 불러오기 도전 - 인터넷방법 
				Uri mImageUri = data.getData();
				mPathGallery= data.getData().getPath();//이거내꺼였음...
				mRealPathGallery = getPath(mImageUri);//이거하면 원 주소 나옴!!
				Log.d("path", mPathCamera + "갤러리: "+mRealPathGallery);
				updateImageView();
				break;
			}//switch
		}//if
	}//onActivityResult
	
	
	 private String getPath(Uri uri) {  
	        String[] projection = { MediaStore.Images.Media.DATA };  
	  
	        Cursor cursor = managedQuery(uri, projection, null, null, null);  
	        int column_index = cursor  
	        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);  
	        cursor.moveToFirst();  
	  
	        return cursor.getString(column_index);  
	    }  
	 
	 
	 private void updateImageView() {  
		 
		 if(code==CALL_CAMERA){
			 
			int degree = ImageUtil.GetExifOrientation(mPathCamera);
			Log.d("degree", degree+"");
			Bitmap resizeBitmap = ImageUtil.loadBackgroundBitmap(AddBookDirectlyActivity.this, mPathCamera);

			if (degree != 0) {
				Bitmap rotateBitmap = ImageUtil.GetRotatedBitmap(resizeBitmap,degree);
				mImage.setImageBitmap(rotateBitmap);
				mImage.setScaleType(ImageView.ScaleType.FIT_XY);
				LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(240,340);
				mImage.setLayoutParams(param);
			} else {// 0이면 안돌려도됨
				mImage.setImageBitmap(resizeBitmap);
				mImage.setScaleType(ImageView.ScaleType.FIT_XY);
				LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(240,340); //계산해서넣었음ㅋㅋ
				mImage.setLayoutParams(param);
			}
			 
		 }else if (code==CALL_GALLERY){
			 
	        int degree = ImageUtil.GetExifOrientation(mRealPathGallery);  
	        Bitmap resizeBitmap = ImageUtil.loadBackgroundBitmap(AddBookDirectlyActivity.this, mRealPathGallery);  
	        
	        if(degree!=0){
	        	Bitmap rotateBitmap = ImageUtil.GetRotatedBitmap(resizeBitmap, degree);  
	 	        mImage.setImageBitmap(rotateBitmap);  
	 	        mImage.setScaleType(ImageView.ScaleType.FIT_XY);
				LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(240,340);
				mImage.setLayoutParams(param);
	        }else{//0이면 안돌려도됨
	        	mImage.setImageBitmap(resizeBitmap);
	        	mImage.setScaleType(ImageView.ScaleType.FIT_XY);
				LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(240,340); //계산해서넣었음ㅋㅋ
				mImage.setLayoutParams(param);
	        }//inner if~else
		 }//if~else
	    } //updateImageView() 

}//end of class


